﻿using System;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using System.Activities;
using System.Activities.Expressions;
using System.Activities.Presentation.PropertyEditing;
using System.Activities.Statements;
using System.Collections.Generic;
using System.ComponentModel;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;

namespace Vision.Core.ActivityComponents.IO.Compression
{
    public class ZipAddFile : NativeActivity
    {
        /// <summary>
        /// 
        /// </summary>
        internal ZipOutputStream ZipStream { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public InArgument<string> ZipFilePath { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public InArgument<byte[]> ZipFileData { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(NativeActivityContext context)
        {
            this.ZipStream = (ZipOutputStream)context.Properties.Find("60D19250-2D72-11E0-BAE7-4BCBDFD72085");
            
            if (this.ZipStream != null){                                    
                byte[] file = context.GetValue(this.ZipFileData);
                
                Crc32 crc = new Crc32();
                crc.Reset();
                crc.Update(file);
                    
                ZipEntry zipEntry = new ZipEntry(ZipEntry.CleanName(context.GetValue(this.ZipFilePath)));
                zipEntry.Size = file.Length;
                zipEntry.DateTime = DateTime.Now;
                zipEntry.Crc = crc.Value;
                                
                this.ZipStream.PutNextEntry(zipEntry);
                this.ZipStream.Write(file,0,file.Length);
                this.ZipStream.CloseEntry();

                file = null;
                zipEntry = null;
                crc = null;
            }
        }
    }
}
